package com.zxx.mvpPractice.common;

import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public abstract class WeakReferenceHandler<T> extends Handler {
    private WeakReference<T> mReference;

    public WeakReferenceHandler(T reference) {
        mReference = new WeakReference<T>(reference);
    }

    public WeakReferenceHandler(Looper looper, T reference) {
        super(looper);
        mReference = new WeakReference<T>(reference);
    }

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        if (mReference.get() == null) {
            Log.d("WeakReferenceHandler", "mReference.get() is null");
            return;
        }

        handleMessage(mReference.get(), msg);
    }

    @Override
    public void dispatchMessage(Message msg) {

        // TODO Auto-generated method stub
        super.dispatchMessage(msg);

        if (mReference.get() == null) {
            Log.d("WeakReferenceHandler", "mReference.get() is null");
            return;
        }

        dispatchMessage(mReference.get(), msg);
    }

    protected abstract void handleMessage(T reference, Message msg);

    protected void dispatchMessage(T reference, Message msg) {

    }

}
